package com.conversationboard.model;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import com.conversationboard.database.Database;
import com.conversationboard.database.Queries;

/**
 * Class to perform the necessary database operations to create a poll and to
 * vote in it.
 * 
 * @author Keith Watson
 * 
 */

public class Poll {

    public static void createPoll(Question question, Connection connection, int boardId, int threadId) throws SQLException {

        PreparedStatement statement = connection.prepareStatement(Queries.INSERT_POLL_OPTIONS);

        for (PollItem option : question.getPollItems()) {
            statement.setInt(1, boardId);
            statement.setInt(2, threadId);
            statement.setInt(3, option.getOptionId());
            statement.setString(4, option.getOptionText());
            statement.addBatch();
        }

        statement.executeBatch();

    }


    public static void vote(int boardId, int threadId, int optionId) throws SQLException {

        Connection connection = Database.getConnection();

        try {
            PreparedStatement statement = connection.prepareStatement(Queries.VOTE);
            statement.setInt(1, boardId);
            statement.setInt(2, threadId);
            statement.setInt(3, optionId);

            statement.execute();

        } finally {
            Database.close(connection);
        }

    }

}
